<?php

namespace Admin\Controller;

use Couchbase\ViewQuery;
use function PHPSTORM_META\elementType;
use function Sodium\add;
use Think\Controller;

class VoiceCallApiController extends Controller
{

    public function __construct()
    {
        header("Content-Type:application/json");
    }

    public function go(){
        header('location:' . 'https://www.baidu.com/');
    }

    /***
     * 今日还款统一调度  早上10点开始
     */
    public function call_today_pay_start()
    {
//        $this->un_cert_voice(1);
//        $this->un_cert_voice(3);
        $url_jk = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/today_pay_voice';
        $url_qxf = 'http://rakf.jiangyuyun.cn/VoiceCallApi/today_pay_voice';
        $this->http($url_jk, '', 0);
        $this->http($url_qxf, '', 0);
//        $this->today_pay_voice(1);//共享
//        $this->today_pay_voice(3);//游呗

    }

    /***
     * 逾期  下午2点开始
     */
    public function call_overdue_start()
    {
        $url_jk = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/overdue_call';
        $url_qxf = 'http://rakf.jiangyuyun.cn/VoiceCallApi/overdue_call';
        $this->http($url_jk, '', 0);
        $this->http($url_qxf, '', 0);
        $this->overdue_call(1);//共享
        $this->overdue_call(3);//游呗
    }

    /***
     * 注册未认证 早上9点开始 和下午4点
     */
    public function call_un_cert_start()
    {

//        $this->un_cert_voice(1);
//        $this->un_cert_voice(3);
//        $url_jk='http://jkkf.jiangyuyun.cn/VoiceCallApi/un_cert_voice';
//        $url_mshb='http://bjkf.dstlkj.com/VoiceCallApi/un_cert_voice';
//        $url_qxf='http://rakf.jiangyuyun.cn/VoiceCallApi/un_cert_voice';
//        $this->http($url_qxf,'',0);
//        $this->http($url_mshb,'',0);
//        $this->http($url_jk,'',0);
////        $this->recent_uncert_voice(1);
////        $this->recent_uncert_voice(3);
        echo 1;
    }

    /**
     * 定时回调  每天晚上  21点
     */
    public function get_callback()
    {
        $url_mshb = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/get_plan_detail';
//        $url_mshb1='http://jkkf.jiangyuyun.cn/VoiceCallApi/get_call_detail';
        $this->http($url_mshb, '', 0);
//        $this->http($url_mshb1,'',0);

        $url_jk = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/get_plan_detail';
        $url_jk1 = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/get_call_detail';
        $url_qxf = 'http://rakf.jiangyuyun.cn/VoiceCallApi/get_plan_detail';
        $url_qxf1 = 'http://rakf.jiangyuyun.cn/VoiceCallApi/get_call_detail';
        $this->http($url_jk, '', 0);
        $this->http($url_jk1, '', 0);
        $this->http($url_qxf1, '', 0);
        $this->http($url_qxf, '', 0);
        $this->get_plan_detail(1);
        $this->get_plan_detail(5);
        $this->get_call_detail();
    }


    public function test()
    {

        $this->get_plan_detail(1);

    }

    /**
     * 定时暂停当日必须任务
     */
    public function paused()
    {
        $url_qxf = 'http://rakf.jiangyuyun.cn/VoiceCallApi/paused_plan';
        $url_jk = 'http://jkkf.jiangyuyun.cn/VoiceCallApi/paused_plan';
        $this->http($url_qxf, '', 0);
        $this->http($url_jk, '', 0);
        $this->paused_plan();
    }

    /**
     * 近期未注册外呼 两天之内
     */
    public function recent_uncert_voice($type)
    {
        $date = date('Y-m-d', time());
        $start_time = strtotime($date . ' 9:01:00') * 1000;
        if ($type == '1') {//共享
            $name = date('YmdHis', time()) . 'GX注册未认证';
            $belong = 1;
            $site_id = '10000825';
            $p_type = 1;
        } else if ($type == '3') {//游呗
            $name = date('YmdHis', time()) . '游呗注册未认证';
            $site_id = '10000828';
            $belong = 2;
            $p_type = 5;
        }

//        $user_id=M('ivr_record','','KEFU')->where(['type'=>$p_type,'user_id'=>['neq',0]])->field('user_id')->order('user_id desc')->limit(1)->find();


        $e_time = strtotime($date) - 24 * 2;
        $s_time = strtotime($date) - 24 * 4;


        $sql = '  SELECT
                        mobile,id
                    FROM
                        dxd_user.`user`
                    WHERE
                      ctime between ' . $s_time . ' and ' . $e_time . ' 
                    AND type = ' . $type . '
                    AND cert_status = 1';

// $sql='SELECT a.mobile,a.id FROM
//                (
//                    SELECT
//                        mobile,id
//                    FROM
//                        dxd_user.`user`
//                    WHERE
//                        ctime BETWEEN 1525104000
//                     AND '.$s_time.'
//                    AND type = '.$type.'
//                    AND cert_status = 1
//                ) a left
//                JOIN dxd_kefu.ivr_callback_record b ON b.phone  = a.mobile
//            AND b.type = 1
//            WHERE  b.phone  is null LIMIT 100';

        $data = M('user', '', 'USER_R')->query($sql);
//        var_dump($data);
//        die;
        $j_arr = array();
        $add_arr = array();
        foreach ($data as $k => $v) {
            $j_arr[] = array('U_phone' => $v['mobile']);
            $add_arr[] = array('phone' => $v['mobile'], 'ctime' => time(), 'type' => $p_type, 'belong' => $belong, 'update_time' => time());
        }

        M('ivr_callback_record', '', 'KEFU')->addAll($add_arr);
        $a = end($data);//数组最后一个
        $ret = $this->c_plan($name, $site_id, $start_time, $j_arr, $p_type, 'NORMAL', $a['id']);
        var_dump($ret);

    }

    /***
     * 注册未认证 - 共享 游呗 语音外呼
     */
    public function un_cert_voice($type)
    {
//        $type=1;
        $date = date('Y-m-d', time());
        $start_time = strtotime($date . ' 9:01:00') * 1000;
        if ($type == '1') {//共享
            $name = date('YmdHis', time()) . 'GX注册未认证';
            $belong = 1;
            $site_id = '10000825';
            $p_type = 1;
        } else if ($type == '3') {//游呗
            $name = date('YmdHis', time()) . '游呗注册未认证';
            $site_id = '10000828';
            $belong = 2;
            $p_type = 5;
        }
        $s_time = strtotime($date) - 48 * 3600;
//        $where = [];
//        $where['c.phone'] =array('exp','is null');
//        $where['a.ctime'] =array('between',[1525104000,$s_time]);
//        $where['a.type'] =array('eq',$type);
//        $where['a.cert_status']=1;
//        $data = M('user', '', 'USER_R')->join('a left join dxd_kefu.ivr_callback_record c on c.phone=a.mobile and c.type=1')->where($where)->limit(100)->field('a.mobile,a.id')->select();

        $user_id = M('ivr_record', '', 'KEFU')->where(['type' => $p_type, 'user_id' => ['neq', 0]])->field('user_id')->order('user_id desc')->limit(1)->find();

//        var_dump($user_id);die;
//
//        $sql='SELECT a.mobile,a.id FROM
//                (
//                    SELECT
//                        mobile,id
//                    FROM
//                        dxd_user.`user`
//                    WHERE
//                      id>'.$user_id['user_id'].'
//                    AND type = '.$type.'
//                    AND cert_status = 1
//                ) a left
//                JOIN dxd_kefu.ivr_callback_record b ON b.phone  = a.mobile
//            AND b.type = 1
//            WHERE  b.phone  is null LIMIT 100';

        $sql = '  SELECT
                        mobile,id
                    FROM
                        dxd_user.`user`
                    WHERE
                      id>' . $user_id['user_id'] . '
                    AND type = ' . $type . '
                    AND cert_status = 1 limit 100';

// $sql='SELECT a.mobile,a.id FROM
//                (
//                    SELECT
//                        mobile,id
//                    FROM
//                        dxd_user.`user`
//                    WHERE
//                        ctime BETWEEN 1525104000
//                     AND '.$s_time.'
//                    AND type = '.$type.'
//                    AND cert_status = 1
//                ) a left
//                JOIN dxd_kefu.ivr_callback_record b ON b.phone  = a.mobile
//            AND b.type = 1
//            WHERE  b.phone  is null LIMIT 100';

        $data = M('user', '', 'USER_R')->query($sql);
//        var_dump($data);
//        die;
        $j_arr = array();
        $add_arr = array();
        foreach ($data as $k => $v) {
            $j_arr[] = array('U_phone' => $v['mobile']);
            $add_arr[] = array('phone' => $v['mobile'], 'ctime' => time(), 'type' => $p_type, 'belong' => $belong, 'update_time' => time());
        }

        M('ivr_callback_record', '', 'KEFU')->addAll($add_arr);
        $a = end($data);//数组最后一个
        $ret = $this->c_plan($name, $site_id, $start_time, $j_arr, $p_type, 'NORMAL', $a['id']);
        var_dump($ret);
    }

    /***
     * 今日应还款 - 共享 游呗 语音外呼
     */
    public function today_pay_voice($type)
    {
        $date = date('Y-m-d', time());
        $start_time = strtotime($date . ' 15:01:00') * 1000;

        if ($type == '1') {
            $name = date('YmdHis', time()) . $type . 'GX今日应还款';
            $site_id = '10000827';
        } else if ($type == '3') {
            $name = date('YmdHis', time()) . $type . '游呗今日应还款';
            $site_id = '10000829';
        }
        //内部人员
        $user = M('testers_mobile', '', 'USER')->getField('mobile', true);
        $where = [];
        $start = strtotime(date('Y-m-d', time()));
        $end = strtotime(date('Y-m-d 23:59:59', time()));
        $where['a.repay_time'] = array('BETWEEN', array($start, $end));
        $where['a.status'] = array('notin', array(3, 5));
        $where['b.type'] = array('eq', $type);
        $where['b.mobile'] = array('notin', $user);
        $data = M('user_repayment', '', 'CAIWU_R')->join('a join dxd_user.user b on a.vid=b.vid')->field('b.mobile')->where($where)->select();
        $j_arr = array();

        foreach ($data as $k => $v) {
            $j_arr[] = array('U_phone' => $v['mobile']);
        }
//        var_dump($j_arr);
        $ret = $this->c_plan($name, $site_id, $start_time, $j_arr, 2, 'HIGH');
        var_dump($ret);
    }

    /**
     * @param:逾期提醒
     * @param:
     */
    public function overdue_call($type)
    {
        $date = date('Y-m-d', time());
        $site_id = '10000756';
        if ($type == '1') {
            $u_project = '共享现金';
            $name = date('YmdHis', time()) . '共享逾期提醒';
        } else if ($type == '3') {
            $u_project = '马上游呗';
            $name = date('YmdHis', time()) . '游呗逾期提醒';
        }

        $user = M('testers_mobile', '', 'USER')->getField('mobile', true);
        $where['a.mobile'] = array('notin', $user);
        $start_time = strtotime($date . ' 14:01:00') * 1000;
        $where['b.status'] = array('eq', 1);
        $where['b.type'] = array('eq', 1);
        $where['a.type'] = array('eq', $type);
        $where['b.overdue_day'] = array('elt', 3);

        $field = 'b.overdue_day,a.mobile';
        $data = M('user_overdue', '', 'URGE_R')->join('b join dxd_user.user a on b.vid = a.vid')->order('b.id desc')->where($where)->field($field)->select();
        $j_arr = array();
        foreach ($data as $k => $v) {
            $j_arr[] = array('U_phone' => $v['mobile'], 'U_project' => $u_project, 'U_overday' => $v['overdue_day']);
        }
//        array_push($j_arr,array('U_phone'=>'13758792879','U_project'=>'共享现金','U_overday'=>'2'));
//        $content = json_encode($j_arr);
//        var_dump($j_arr);
        $result = $this->c_plan($name, $site_id, $start_time, $j_arr, 4, 'HIGH');
        var_dump($result);
    }

    /**
     * 获取计划执行详情  即 外呼详情
     * 一次最多100条，超过的要多次调用
     * 未接听到的用户，记录拨打次数
     *
     */
    public function get_plan_detail($type)
    {
//        $plans=M('ivr_record','','KEFU')->where(['id'=>['in',[68,67,71]]])->field('campaign_id,type,total')->select();

        $plans = M('ivr_record', '', 'KEFU_R')->where(['has_callback' => 0, 'type' => $type, 'total' => ['gt', 0]])->field('campaign_id,type,total')->select();
        foreach ($plans as $k => $v) {
            $campaign_id = $v['campaign_id'];
            $url = 'https://open.duyansoft.com/api/v1/call/campaign/' . $campaign_id . '/item?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&page_num=1&page_size=100&outcome=SUCCESS';
            $header = array('Content-Type:application/json');
            $ret = $this->http($url, '', 0, $header);
            $data = json_decode($ret, true);
            $d = $data['data']['campaigns'];
            foreach ($d as $k1 => $v1) {
                $arr = array('call_long' => $v1['duration'], 'outcome' => 'SUCCESS', 'call_time' => $v1['call_time']);
                M('ivr_callback_record', '', 'KEFU')->where(['type' => $type, 'phone' => $v1['phone']])->save($arr);
            }
            $count = count($d);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('callback_num', $count);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('has_callback', 1);
        }
        $ret = json_decode($ret, true);
        var_dump($ret);
    }

    /***
     * 今日还款 和 逾期提醒的电话详情
     */
    public function get_call_detail()
    {
        $plans = M('ivr_record', '', 'KEFU')->where(['has_callback' => 0, 'type' => ['neq', 1]])->field('campaign_id,type')->select();
        foreach ($plans as $k => $v) {
            $campaign_id = $v['campaign_id'];
            $url = 'https://open.duyansoft.com/api/v1/call/campaign/' . $campaign_id . '/item?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&page_num=1&page_size=100&outcome=SUCCESS';
            $header = array('Content-Type:application/json');
            $ret = $this->http($url, '', 0, $header);
            $data = json_decode($ret, true);
            $d = $data['data']['campaigns'];
            $arr = array();
            foreach ($d as $k1 => $v1) {
                $arr[] = array('call_long' => $v1['duration'], 'outcome' => 'SUCCESS', 'type' => $v['type'], 'phone' => $v1['phone'], 'ctime' => time(), 'call_time' => $v1['call_time']);
            }
            M('ivr_callback_record', '', 'KEFU')->addAll($arr);
            $count = count($d);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('callback_num', $count);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('has_callback', 1);
        }
        var_dump($ret);
    }

    /**
     * http请求
     * @param  string $url 请求地址
     * @param  boolean|string|array $params 请求数据
     * @param  integer $ispost 0/1，是否post
     * @param  array $header
     * @param  $verify 是否验证ssl
     * return string|boolean          出错时返回false
     */
    function http($url, $content, $ispost = 1, $header = [], $verify = false)
    {
        $httpInfo = array();
        $ch = curl_init();
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        //忽略ssl证书
        if ($verify === true) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if (is_array($content)) {
                $params = http_build_query($content);
            }
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);
        if ($response === FALSE) {
            trace("cURL Error: " . curl_errno($ch) . ',' . curl_error($ch), 'error');
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
            trace($httpInfo, 'error');
            return false;
        }
        curl_close($ch);
        return $response;
    }

    function dbSaveAll($datas, $database_table_name, $primary_key)
    {
        $primary_key = $primary_key;
        $sql = ''; //Sql
        $lists = []; //记录集$lists
        $pk = $primary_key;//获取主键
        foreach ($datas as $data) {
            foreach ($data as $key => $value) {
                if ($pk === $key) {
                    $ids[] = $value;
                } else {
                    $lists[$key] .= sprintf("WHEN %u THEN '%s' ", $data[$pk], $value);
                }
            }
        }
        foreach ($lists as $key => $value) {
            $sql .= sprintf("`%s` = CASE `%s` %s END,", $key, $pk, $value);
        }
        $sql = sprintf('UPDATE %s SET %s WHERE %s IN ( %s )', $database_table_name, rtrim($sql, ','), $pk, implode(',', $ids));
        return $sql;
    }

    /**
     * 计划创建
     */
    public function voice_test($name = 'test', $site_id = '10000788', $start_time = '', $j_arr, $type = 1)
    {
        $j_arr = array('U_phone' => '13758792879');
        $content = json_encode($j_arr);
        if ($type == 1) {
            $url = 'https://open.duyansoft.com/api/v2/call/campaign/auto?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&name=' . $name . '&site_id=' . $site_id . '&channel_limit=1&retry_count=2&retry_interval=30&is_distinct=true&caller=57156973731&start_time=' . $start_time;
        } else {
            $url = 'https://open.duyansoft.com/api/v2/call/campaign/auto?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&name=' . $name . '&site_id=' . $site_id . '&channel_limit=1&retry_count=2&retry_interval=60&is_distinct=true&caller=57156973731&start_time=' . $start_time;
        }
        $header = array('Content-Type:application/json');
        $ret = $this->http($url, $content, 1, $header);
        $result = json_decode($ret, true);

        return $result;
    }

    /**
     *   审核通过语音 接口
     */
    public function pass_voice()
    {
        $type = I('post.type');//1 共享 2游呗 3旅游白卡 4 趣消费 5易旅游i 6 yilvyou退款 7 马上花呗 8快借钱 9 东京白条
        $phone = I('post.phone');

        $start_time = time() * 1000;
        $mobile[] = array('U_phone' => $phone);

        $call_type = 0;
        switch ($type) {
            case '1':
                $name = '共享审核通过语音';
                $site_id = '10000818';
                $call_type = 6;
                break;
            case '2':
                $name = '游呗审核通过语音';
                $site_id = '10000821';
                $call_type = 7;
                break;
            case '3':
                $name = '旅游白卡审核通过语音';
                $site_id = '10000820';
                $call_type = 8;
                break;
            case '4':
                $url_qxf = 'http://rakf.jiangyuyun.cn/VoiceCallApi/qxf_pass_voice';
                $param = array('phone' => $phone);
                $ret = $this->http($url_qxf, $param, 1);
                break;
            case '5':
                $name = '易旅游退单提现语音';
                $site_id = '10000810';
                $phone_arr = explode(',', $phone);
                $num = count($phone_arr);
                for ($i = 0; $i < $num; $i++) {
                    $mobile[] = array('U_phone' => $phone_arr[$i]);
                }
                $call_type = 10;
                break;
            case '6':
                $name = '易旅游退款提醒语音';
                $site_id = '10000944';
                $phone_arr = explode(',', $phone);
                $num = count($phone_arr);
                for ($i = 0; $i < $num; $i++) {
                    $mobile[] = array('U_phone' => $phone_arr[$i]);
                }
                $call_type = 11;
                break;
            case '7':
                $mshb_qxf = 'http://bjkf.dstlkj.com/VoiceCallApi/mshb_pass_voice';
                $param = array('phone' => $phone);
                $ret = $this->http($mshb_qxf, $param, 1);
                break;
            case '8':
                $kj_qxf = 'https://kjkf.gscfjt.com/VoiceCallApi/kj_pass_voice';
                $param = array('phone' => $phone);
                $ret = $this->http($kj_qxf, $param, 1);
                break;
            case '9':
                $dj_qxf = 'https://jdkf.zknfmy.com/VoiceCallApi/dj_pass_voice';
                $param = array('phone' => $phone);
                $ret = $this->http($dj_qxf, $param, 1);
                break;
        }

        $ret = json_decode($ret, true);
        $arr=['4','7','8','9'];

        if (!in_array($type,$arr)) {
            $ret = $this->c_plan($name, $site_id, $start_time, $mobile, $call_type, 'HIGH');
            $ret['status'] == '1';
        }

        if ($ret['status'] == '1') {
            $this->ajaxReturn(array('code' => '1001', 'result' => '请求成功', 'message' => $ret['message']));
        } else {
            $this->ajaxReturn(array('code' => '1002', 'result' => '请求失败', 'message' => $ret['message']));
        }

    }

    /**
     * 未认证三天内没有接通的删除掉
     */
    public function del_un_cert(){
//        $where['ctime']=array('lt',time()-72*3600);
//        $where['type']=1;
//        $where['outcome']=array('neq','SUCCESS');
//        $del=M('ivr_callback_record','','KEFU')->where($where)->delete();
    }

    public function cert_total()
    {
        $where['a.type'] = 1;
        $where['a.ctime'] = ['lt', 1535904000];
        $where['a.outcome'] = 'SUCCESS';
        $data = M('ivr_callback_record', '', 'KEFU')->join('a join dxd_user.user b on b.mobile=a.phone')->where($where)->field('call_time,cert_time,cert_status,vid')->select();
        $count = 0;
        $pass = 0;
        $nopass = 0;
        $certing = 0;
        $check = 0;
        $wait_c = 0;
        foreach ($data as $k => $v) {
            $call_t = $v['call_time'] / 1000;
//             $cert_t=M('user_examine','','RISK_R')->where(['vid'=>$v['vid']])->getfield('ctime');
            $cert_t = M('user_idcard_img', '', 'USER_R')->where(['vid' => $v['vid']])->getfield('ctime');
            if ($call_t < $cert_t) {
                $count++;
                switch ($v['cert_status']) {
                    case 2:
                        $pass++;
                        break;
                    case 3:
                        $nopass++;
                        break;
                    case 4:
                        $certing++;
                        break;
                    case 5:
                        $check++;
                        break;
                    case 6:
                        $wait_c++;
                        break;
                }
            }
//             if($v['cert_status']==4){
//                 $certing++;
//             }

        }
        var_dump(array('tol' => $count, 'pass' => $pass, 'nopass' => $nopass, 'certing' => $certing, 'check' => $check, 'wait_c' => $wait_c));

    }

    /**
     * 计划创建
     */
    public function c_plan($name, $site_id, $start_time, $j_arr, $type, $priority = 'NORMAL', $user_id)
    {
        $total = count($j_arr);
        $content = json_encode($j_arr);
//        if($type==1){//1 未认证 2 认证通过 其他 逾期和还款
        $url = 'https://open.duyansoft.com/api/v2/call/campaign/auto?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&name=' . $name . '&site_id=' . $site_id . '&channel_limit=1&retry_count=1&retry_interval=30&is_distinct=true&start_time=' . $start_time . '&priority=' . $priority;
//        }else if($type==2){//1 未认证 2 认证通过 其他 逾期和还款
//            $url = 'https://open.duyansoft.com/api/v2/call/campaign/auto?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&name=' . $name . '&site_id='.$site_id.'&channel_limit=1&retry_count=1&retry_interval=30&is_distinct=true&caller=57156973731&start_time=' . $start_time.'&priority='.$priority;
//        }else{
//            $url = 'https://open.duyansoft.com/api/v2/call/campaign/auto?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&name=' . $name . '&site_id='.$site_id.'&channel_limit=1&retry_count=1&retry_interval=30&is_distinct=true&caller=57156973731&start_time=' . $start_time.'&priority='.$priority;
//        }


        $header = array('Content-Type:application/json');
        $ret = $this->http($url, $content, 1, $header);
        $result = json_decode($ret, true);
        if ($result['status'] == '1') {
            $arr = array('user_id' => $user_id, 'ctime' => time(), 'type' => $type, 'c_date' => date('Y-m-d H:i:s', time()), 'content' => 'success', 'campaign_id' => $result['data']['id'], 'name' => $name, 'total' => $total);
        } else {
            $arr = array('user_id' => $user_id, 'ctime' => time(), 'type' => $type, 'c_date' => date('Y-m-d H:i:s', time()), 'content' => '调用失败', 'campaign_id' => $result['data']['id'], 'name' => $name);
        }
        M('ivr_record', '', 'KEFU')->add($arr);
        return $result;
    }

    /***
     * 今日还款 和 逾期提醒的电话详情
     */
    public function get_call_detail1()
    {
        $plans = M('ivr_record', '', 'KEFU')->where(['has_callback' => 0, 'type' => ['eq', 10]])->field('campaign_id,type')->select();
        foreach ($plans as $k => $v) {
            $campaign_id = $v['campaign_id'];
            $url = 'https://open.duyansoft.com/api/v1/call/campaign/' . $campaign_id . '/item?apikey=sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N&page_num=1&page_size=100&outcome=SUCCESS';
            $header = array('Content-Type:application/json');
            $ret = $this->http($url, '', 0, $header);
            $data = json_decode($ret, true);
            $d = $data['data']['campaigns'];
            $arr = array();
            foreach ($d as $k1 => $v1) {
                $arr[] = array('call_long' => $v1['duration'], 'outcome' => 'SUCCESS', 'type' => $v['type'], 'phone' => $v1['phone'], 'ctime' => time(), 'call_time' => $v1['call_time']);
            }
            M('ivr_callback_record', '', 'KEFU')->addAll($arr);
            $count = count($d);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('callback_num', $count);
            M('ivr_record', '', 'KEFU')->where(['campaign_id' => $campaign_id])->setField('has_callback', 1);
        }
        var_dump($ret);
    }


    /**
     * 今日还款和逾期 当日没呼完则暂停
     */
    public function paused_plan()
    {

        $where = [];
//        $where['ctime'] = ['lt', 1546358400];
        $where['ctime'] = ['between', [1545379200,1546358400]];
//        $where['ctime'] = ['between', [strtotime(date('Y-m-d', time())), time()]];
//        $where['type'] = ['in', [2, 4]];
        $data = M('ivr_record', '', 'KEFU')->where($where)->field('campaign_id')->select();
        foreach ($data as $k => $v) {
            $url = 'https://open.duyansoft.com/api/v1/call/campaign/' . $v['campaign_id'] . '/status';
            $this->http($url, array('campaign_status' => 'PAUSED', 'apikey' => 'sEcY7RvxFXNE6a40kUVXvJswdYG6GG5N'), 1);
        }
    }

    /**
     * 未认证 转化 度言
     */
    public function dy_un_cert()
    {
        $this->get_plan_detail(5);

        die;
        $pro = I('project');//1共享 3 游呗
        $start_time = I('start_time');//外呼时间
        $end_time = I('end_time');//

        $where['ctime'] = ['between', [$start_time, $end_time]];
        $where['b.type'] = $pro;
        //总的外呼
        $total = M('ivr_record', '', 'KEFU_R')->where(['type' => ['in', [1, 5]], 'has_callback' => 1, 'content' => 'success'])->sum('total');
        //接通外呼
        $get_total = M('ivr_callback_record', '', 'KEFU_R')->where(['type' => 1, 'outcome' => 'SUCCESS'])->count();
        //转化
        $data = M('ivr_callback_record', '', 'KEFU_R')->join('a join dxd_user.user b on b.mobile=a.phone')->where(['a.type' => 1, 'a.outcome' => 'SUCCESS'])->field('b.truename,b.mobile,b.vid,a.call_time,cert_status')->select();
        $in24 = 0;//24小时内去认证数
        $out24 = 0;//
        $no_cert = 0;//为认证
        $pass24 = 0;
        $refuse24 = 0;
        $check24 = 0;//审核中
        $wait_check24 = 0;//待审核
        $g_time = M('user_examine', '', 'ROM_DQSH')->where(['vid' => ['in', array_column($data, 'vid')]])->getfield('vid,ctime', true);

        foreach ($data as $k => $v) {
//            $g_time=M('user_examine','','ROM_DQSH')->where(['vid'=>$v['vid']])->getfield('ctime');
            if ($g_time[$v['vid']] < ($v['call_time'] / 1000) * 24 * 3600 && $g_time[$v['vid']] > ($v['call_time'] / 1000) && !empty($g_time[$v['vid']])) {
                $in24++;
                switch ($v['cert_status']) {
                    case 2:
                        $pass24++;
                        break;
                    case 3:
                        $refuse24++;
                        break;
                    case 4:
                        $check24++;
                        break;
                    case 6:
                        $wait_check24++;
                        break;
                }
            } else if ($g_time[$v['vid']]) {
                $out24++;
            } else {
                $no_cert++;
            }
        }
        $ret['总的外呼'] = $total;
        $ret['接通外呼'] = $get_total;
        $ret['in24'] = $in24;
        $ret['out24'] = $out24;
        $ret['nono'] = $no_cert;
        $ret['pass24'] = $pass24;
        $ret['refused24'] = $refuse24;
        $ret['check24'] = $check24;
//        $this->assign(['data'=>$ret]);

        var_dump($ret);
    }


    //===========每天客服电话统计

    /**
     *  每天最后的接通率
     */


    /**
     * 12 ，16点统计下  有则修改否则添加
     */

    public function kefu_call_statics()
    {

        $today_time = strtotime(date('Y-m-d', time()));
        $add_arr = [];
        //注册未认证
        $un_cert = M('kefu_ownuser', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid')
            ->where(['a.type' => 3, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');
        $un_cert_true = M('kefu_ownuser', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid and c.state=1')
            ->where(['a.type' => 3, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');

        $add_arr['uncert_rate'] = get_two($un_cert_true, $un_cert) * 100;

        //今日需还款列表
        $today_pay = M('temp_today_pay_mark', '', 'KEFU')->where(['ctime' => ['between', [$today_time, time()]]])->count('DISTINCT vid');
        $today_pay_true = M('temp_today_pay_mark', '', 'KEFU')->where(['ctime' => ['between', [$today_time, time()]], 'reason' => ['like', '%已告知%']])->count('DISTINCT vid');
        $add_arr['today_pay_rate'] = get_two($today_pay_true, $today_pay) * 100;


        //近期注册未认证列表
        $un_cert_recent = M('kf_snatch', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid')
            ->where(['a.type' => 1, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');

        $un_cert_recent_true = M('kf_snatch', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid  and c.state=1')
            ->where(['a.type' => 1, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');
        $add_arr['recent_uncert_rate'] = get_two($un_cert_recent_true, $un_cert_recent) * 100;


        //认证未完成
        $un_finish_recent = M('kf_snatch', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid')
            ->where(['a.type' => 2, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');

        $un_finish_recent_true = M('kf_snatch', '', 'KEFU')
            ->join('a join dxd_kefu.call_info c on c.vid=a.vid  and c.state=1')
            ->where(['a.type' => 2, 'c.ctime' => ['between', [$today_time, time()]]])
            ->count('DISTINCT a.vid');

        $add_arr['cert_unfinish'] = get_two($un_finish_recent_true, $un_finish_recent) * 100;


        //逾期用户

        $today_overdue = M('mark', '', 'KEFU')->where(['ctime' => ['between', [$today_time, time()]]])->count('DISTINCT repayment_no');
        $wh['ctime'] = ['between', [$today_time, time()]];
        $wh['reason'] = ['like', '%已告知%'];
        $today_overdue_true = M('mark', '', 'KEFU')->where($wh)->count('DISTINCT repayment_no');

        $add_arr['overdue_rate'] = get_two($today_overdue_true, $today_overdue) * 100;
        $add_arr['time'] = time();

        $exit = M('kefu_day_statics', '', 'KEFU')->where(['time' => ['between', [$today_time, time()]]])->find();
        if ($exit['id']) {
            M('kefu_day_statics', '', 'KEFU')->where(['id' => $exit['id']])->save($add_arr);
        } else {
            M('kefu_day_statics', '', 'KEFU')->add($add_arr);
        }

//         M('kefu_day_statics','','KEFU')->add($add_arr);
//         var_dump($add_arr);
    }


    //用户信息修改 保存
    public function user_save()
    {
        $_POST['user_name']='hejing';

        foreach ($_POST as  $k=>$v){
            if(!empty($_POST[$k])){
                switch ($k){
                    case 'user_name':  $param['truename'] =$v;  break;
                    case 'select_sex':  $param['sex'] =$v;  break;
                    case 'select_marry':  $param['ismarry'] =$v;  break;
                    case 'degree':  $param['degree'] =$v;  break;
                    case 'id_card':  $param['id_card'] =$v;  break;
                    case 'live_address':  $param['address'] =$v;  break;
                    case 'live_time':  $param['residence_time'] =$v;  break;
                }
            }
        }
//     var_dump($_POST);
    }

}